#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <cstdlib>
#include <cstdint>
#include <ctime>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* head;
    ListNode* head2;
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* head = NULL;
        ListNode* nodePre = NULL;
        while(1){
            if (l1 && l2){
                if (l1->val < l2->val){
                    ListNode* node = new ListNode(l1->val);
                    if (nodePre){
                        nodePre->next = node;
                    }
                    nodePre = node;
                    if (!head){
                        head = nodePre;
                    }
                    l1 = l1->next;
                }else{
                    ListNode* node = new ListNode(l2->val);
                    if (nodePre){
                        nodePre->next = node;
                    }
                    nodePre = node;
                    if (!head){
                        head = node;
                    }
                    l2 = l2->next;
                }
            }else if (l1){
                ListNode* node = new ListNode(l1->val);
                if (nodePre){
                    nodePre->next = node;
                }
                nodePre = node;
                if (!head){
                    head = nodePre;
                }
                l1 = l1->next;
            }else if (l2){
                ListNode* node = new ListNode(l2->val);
                if (nodePre){
                    nodePre->next = node;
                }
                nodePre = node;
                if (!head){
                    head = nodePre;
                }
                l2 = l2->next;
            }else{
                break;
            }
        }
        return head;
    }
};

ListNode* createList(int num, uint32_t max)
{
    ListNode* head;
    ListNode* node;
    if (0 == num) return NULL;
    srand(clock());
    head = new ListNode(rand()%max);
    node = head;
    for (int i = 0; i < num-1; i++){
        node->next = new ListNode(rand()%max);
        node = node->next;
    }
    return head;
}

void printList(ListNode* node)
{
    int cnt = 0;
    cout << "node print start:" << endl;
    while(node){
        cout << ++cnt << ":" << node->val << endl;
        node = node->next;
    }
    cout << "node print end" << endl;
}

int main(void)
{
    Solution su;
    su.head = createList(30, 100);
    su.head2 = createList(30, 100);
    printList(su.head);
    printList(su.head2);
    ListNode* list = su.mergeTwoLists(su.head, su.head2);
    printList(list);
    return 0;
}
